package br.com.sca.basecrud.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import br.com.sca.basecrud.GenericDao;
import br.com.sca.exception.DaoException;

public class GenericDaoImpl<T> implements GenericDao<T> {

	private Class<T> persistClass;

	@Autowired
	private SessionFactory sessionFactory;

	public GenericDaoImpl(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
		this.persistClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	protected Session getSession() {
		return SessionFactoryUtils.openSession(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T pesquisarPorId(Serializable id) throws DaoException {
		return (T) getSession().getSessionFactory().getCurrentSession().get(this.persistClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll() throws DaoException {
		return getSession().getSessionFactory().getCurrentSession().createCriteria(this.persistClass).list();
	}

	@Override
	public void persistirEntidade(T entity) throws DaoException {
		getSession().getSessionFactory().getCurrentSession().save(entity);
	}

	@Override
	public void excluirEntidade(T entity) throws DaoException {
		getSession().getSessionFactory().getCurrentSession().delete(entity);

	}

	@Override
	public void updateEntidade(T entity) throws DaoException {
		getSession().getSessionFactory().getCurrentSession().merge(entity);

	}

}
